package com.ctbu.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctbu.entity.FinancialProduct;
import com.ctbu.entity.Users;
import com.ctbu.service.UsersService;
import com.ctbu.tools.HttpStatusEnum;
import com.ctbu.tools.ResponseResult;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * <p>
 * 用户表，包含用户ID、用户名称和用户密码等信息 前端控制器
 * </p>
 *
 * @author lli
 * @since 2024年06月27日
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    UsersService usersService;

    /**
     * 按id查询
     * @param id
     * @return
     */

    @GetMapping("/remote/{id}")
    public Users queryUsersById(@PathVariable int id){
        return usersService.getById(id);
    }

    /**
     * 查询所有数据（增加或修改显示信息使用）
     * @return
     */
    @GetMapping("/queryAll")
    public ResponseResult<Object> queryAll(){
        List<Users> list = usersService.list();
        return ResponseResult.success(list,"查询成功");

    }

    /**
     * 登录
     */
    @PostMapping("/checkLogin")
    public ResponseResult<Object> checkLogin(HttpServletRequest request, @RequestBody Users users){
        //读取存储的验证码
        ServletContext context=request.getServletContext();
        String backCode=(String) context.getAttribute("backCode");
        //先验证前端传过来的验证码是否和保存的一致
        if(!backCode.equalsIgnoreCase(users.getVerifyCode())){
            return ResponseResult.error(HttpStatusEnum.INTERNAL_SERVER_ERROR,"验证码错误");
        }
        //验证账号密码信息
        LambdaQueryWrapper<Users> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUserName,users.getUserName());
        wrapper.eq(Users::getUserPassword,users.getUserPassword());
        Users user=usersService.getOne(wrapper);
        if(user==null){
            return ResponseResult.error(HttpStatusEnum.INTERNAL_SERVER_ERROR,"账号或密码错误");
        }
        //脱敏
        user.setUserPassword("******");
        return ResponseResult.success(user,"登陆成功");
    }



}
